package run.iget.admin.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import run.iget.admin.system.entity.AdministratorDepartment;
import run.iget.admin.system.entity.table.AdministratorDepartmentTableDef;
import run.iget.admin.system.mapper.AdministratorDepartmentMapper;
import run.iget.admin.system.service.AdministratorDepartmentService;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 * 管理员-部门关联表 服务实现类
 * </p>
 *
 * @author 大周
 * @since 2022-02-07
 */
@Service
public class AdministratorDepartmentServiceImpl extends
        ServiceImpl<AdministratorDepartmentMapper, AdministratorDepartment> implements AdministratorDepartmentService {

    @Override
    public void relationDepartment(Long administratorId, List<Long> departmentIds) {
        // 删除之前管理的角色
        this.remove(AdministratorDepartmentTableDef.ADMINISTRATOR_DEPARTMENT.ADMINISTRATOR_ID.eq(administratorId));
        if (CollectionUtil.isNotEmpty(departmentIds)) {
            List<AdministratorDepartment> administratorDepartmentList = new ArrayList<>(departmentIds.size());
            AdministratorDepartment administratorDepartment = null;
            for (Long departmentId : departmentIds) {
                administratorDepartment = new AdministratorDepartment();
                administratorDepartment.setAdministratorId(administratorId);
                administratorDepartment.setDepartmentId(departmentId);
                administratorDepartmentList.add(administratorDepartment);
            }
            this.saveBatch(administratorDepartmentList);
        }
    }

    @Override
    public List<AdministratorDepartment> query(AdministratorDepartment administratorDepartment) {
        return this.list(QueryWrapper.create(administratorDepartment));
    }

    @Override
    public List<Long> getDepartmentIdsByUserId(Long administratorId) {
        AdministratorDepartment administratorDepartment = new AdministratorDepartment();
        administratorDepartment.setAdministratorId(administratorId);
        List<AdministratorDepartment> query = this.query(administratorDepartment);
        return Optional.ofNullable(query).orElse(new ArrayList<>(0)).stream()
                .map(AdministratorDepartment::getDepartmentId).collect(Collectors.toList());
    }
}
